package com.ciaojian.store.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.core.enums.business.MemberOrderTypeEnum;
import com.ciaojian.core.mapper.MemberOrderMapper;
import com.ciaojian.core.model.MemberOrder;
import com.ciaojian.core.model.ao.DataDashboardAO;
import com.ciaojian.core.service.MemberOrderService;
import com.ciaojian.store.model.bo.OperationMemberOrderBO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author Atlakyn
 */
@Service
public class MemberOrderServiceImpl extends MemberOrderService<MemberOrderMapper, MemberOrder> {
    /**
     * 按条件查询会员卡销售额
     *
     * @param params 查询条件
     * @return 会员卡销售额
     */
    public BigDecimal sumMoney(DataDashboardAO params) {
        QueryWrapper<MemberOrder> wrapper = new QueryWrapper<>();
        wrapper.select("ifnull(sum(money),0) as memberMoneyTotal");
        wrapper.lambda().ge(params.getStartDate() != null, MemberOrder::getCreateTime, params.getStartDate())
                .le(params.getEndDate() != null, MemberOrder::getCreateTime, params.getEndDate())
                .eq(params.getStoreId() != null, MemberOrder::getStoreId, params.getStoreId())
                .eq(MemberOrder::getStatus, MemberOrderTypeEnum.renew)
        ;

        Map<String, Object> map = this.getMap(wrapper);
        return MapUtil.get(map, "memberMoneyTotal", BigDecimal.class);
    }


    /**
     * 按条件查询会员卡订单数
     *
     * @param params 查询参数
     * @return 订单数
     */
    public Integer countMemberOrder(DataDashboardAO params) {
        LambdaQueryWrapper<MemberOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(params.getStartDate() != null, MemberOrder::getCreateTime, params.getStartDate())
                .le(params.getEndDate() != null, MemberOrder::getCreateTime, params.getEndDate())
                .eq(params.getStoreId() != null, MemberOrder::getStoreId, params.getStoreId())
                .eq(MemberOrder::getStatus, 1);
        return this.count(wrapper);
    }


    /**
     * 运营端查询订单
     *
     * @param params 查询参数
     * @return 查询结果
     */
    public List<Object> findByOperationMemberOrderBO(OperationMemberOrderBO params) {
        return baseMapper.findByOperationMemberOrderBO(BeanUtil.beanToMap(params), new Page(params.getPageNo(), params.getPageSize()));
    }
}
